package com.traffic.between.adaptor;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.traffic.between.annotation.ChooseProvider;
import com.traffic.between.config.OrderInfoContext;
import com.traffic.between.redis.running.BsmOrderResultExecutor;
import com.traffic.between.service.MaiFengServiceImpl;
import com.traffic.managent.service.order.bean.OrderBean;

import net.sf.json.JSONObject;

@ChooseProvider(channel = "maifeng")
public class MaiFengAdaptor implements IAdaptor{

	private static Logger log = Logger.getLogger(MaiFengAdaptor.class);

	public void order() {

		// 获取当前OrderBean
		OrderBean orderBean = OrderInfoContext.getContext();
		orderBean.setSendTime(new Date());
		String productId = orderBean.getProductCode();
		String phoneNo = orderBean.getPhoneNo();
		String cstmOrderNo = orderBean.getIds();

		log.info("between- 麦峰通信流量订购接口请求参数:productId=" + productId+",phoneNo="+phoneNo+",cstmOrderNo="+cstmOrderNo);
		
		String result = MaiFengServiceImpl.service.order(productId, phoneNo, cstmOrderNo);
		
		log.info("between- 麦峰通信流量订购接口返回数据为:[" + result+"],该订单号为："+cstmOrderNo);

		JSONObject json = JSONObject.fromObject(result);

		// 订购响应后 赋值 suppCstNo

		String code = (String) json.get("code");

		if (("0".equals(code))) {
			orderBean.setMessage((String) json.get("msg"));
			orderBean.setErrorMsg("订购中");
			orderBean.setStatus("11");
		} else {
			orderBean.setMessage((String) json.get("msg"));
			orderBean.setErrorMsg("订购失败");
			orderBean.setStatus("8");
		}

		BsmOrderResultExecutor.service.setOrder(orderBean);
	}

	
	public void status() {

		// 获取当前OrderBean
		OrderBean orderBean = OrderInfoContext.getContext();

		String cstmOrderNo = orderBean.getIds();

		String result = MaiFengServiceImpl.service.orderStatus(cstmOrderNo);
		log.info("between- 麦峰通信流量订购状态查询接口返回数据为 ：" + result);

		JSONObject json = JSONObject.fromObject(result);

		String code = (String) json.get("code");
		Map<String, String> resultMap = new HashMap<String, String>();
		/**
		 * 0：订单已接收 1：充值成功 4：平台库存不足 5：充值失败 6：订单错误 7：订单充值中
		 */
		String status = "";
		if ("0".equals(code)) {
			resultMap = (Map<String, String>) json.get("data");
			status = resultMap.get("status");

			if ("0".equals(status) || resultMap == null || "7".equals(status)) {
				orderBean.setMessage((String) json.get("msg"));
				orderBean.setErrorMsg("订购中");
				orderBean.setStatus("1");

			} else if ("1".equals(status)) {
				orderBean.setErrorMsg("充值成功");
				orderBean.setStatus("7");
			} else {
				orderBean.setErrorMsg("订购失败");
				orderBean.setStatus("8");
			}

		} else {
			if ("30".equals(code)) {// 上游没有订单。做受理中处理
				orderBean.setErrorMsg("无订单");
				orderBean.setStatus("");
			} else {
				orderBean.setErrorMsg("订购失败");
				orderBean.setStatus("8");
				orderBean.setErrorMsg((String) json.get("msg"));

			}

		}
		BsmOrderResultExecutor.service.setOrder(orderBean);
	}
	
}
